package com.lnu.information.util;

import ws.schild.jave.Encoder;
import ws.schild.jave.MultimediaObject;
import ws.schild.jave.encode.AudioAttributes;
import ws.schild.jave.encode.EncodingAttributes;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author : jian.zhang-2
 * @description:
 * @date : Create in 8:06 PM 2021/9/23
 * @modified By :
 */
public class Video2AudioUtil {

    public static String TARGET_FILE_PATH = "/Users/zhangjian/Downloads/";

    /***
     * 斜杠/
     */
    public static String SLASH = "/";

    /***
     * 视频转音频
     * @param filePath
     */
    public void video2Audio(String filePath){
        try {
            List<String> fileNameList = new ArrayList<String>();
            //获取输入路径下的所有文件
            SpirePdfUtil.folderMethod(filePath, fileNameList);
            //遍历
            for(int i = 0; i < fileNameList.size(); i++){
                //获取当前文件路径
                String source = fileNameList.get(i);
                //如果是以mp4或者flv结尾的文件，则是视频文件
                if(source.endsWith("mp4") || source.endsWith("flv")) {
                    //组装目标文件路径
                    String target = getTarget(source);
                    //正式进行视频转音频
                    video2Audio(source, target);
                }
            }
        }catch (Exception e){
            e.getStackTrace();
        }
    }

    /***
     * 视频转音频
     * @param source 源文件路径
     * @param target 目标文件路径
     */
    public String video2Audio(String source, String target) {
        try {
            File sourceFile = new File(source);
            File targetFile = new File(target);
            //组装多媒体文件对象
            MultimediaObject multimediaObject = new MultimediaObject(sourceFile);
            AudioAttributes audio = new AudioAttributes();
            //设置编码格式
            audio.setCodec("pcm_s16le");
            EncodingAttributes attrs = new EncodingAttributes();
            //设置转换后的格式
            attrs.setOutputFormat("wav");
            attrs.setAudioAttributes(audio);
            Encoder encoder = new Encoder();
            //编码
            encoder.encode(multimediaObject, targetFile, attrs);
        }catch (Exception e){
            e.printStackTrace();
        }
        return target;
    }

    /***
     * 组装目标文件路径
     * @param source
     * @return
     */
    public String getTarget(String source) {
        //将源文件路径当前的文件夹名和文件名保存，组装成目标文件路径
        //将文件名后缀改为wav
        String target = source.substring(0, source.lastIndexOf("."));
        target = target + ".wav";
        return target;
    }

}
